Imports cmplib01



Public Class ctlCombatResolution

    'TODO: Change battle outcome

    'TODO: Change chitmember status

    'TODO: Change installationchit ownership

    '// set the outcome of each battle as well as set the status of units/battlegroup

    Public Event AllBattlesFinished()

    Private ptrGameData As CampaignerGameData
    Private ptrFlexMap As FMPLib01.FlexMapData



#Region "Painting"
    Private Sub pnlSecondary_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles pnlSecondary.Paint
        e.Graphics.DrawImage(My.Resources.selectedchitleftCap, New Point(0, 0))
    End Sub

    Private Sub paintPropertiesEndCap(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles lblTerrainDetails.Paint, lblChitsInvolved.Paint
        e.Graphics.DrawImage(My.Resources.subPropertyLeftCap, New Point(0, 0))
    End Sub
#End Region


    Public Sub ListBattles(ByRef GameData As cmplib01.CampaignerGameData, ByRef fmpMap As FMPLib01.FlexMapData)
        Try
            '// clear old data
            lstBattles.Items.Clear()
            txtTerrainDetails.Text = "Select a battle."
            tvwChits.Nodes.Clear()

            ptrGameData = GameData
            ptrFlexMap = fmpMap

            For Each key As String In ptrGameData.Battles_g.HT.Keys
                Dim lvwi As New ListViewItem
                lvwi.Text = ptrGameData.Battles_g.Item(key).BattleName
                lvwi.Tag = ptrGameData.Battles_g.Item(key)
                ShowResultIcon(lvwi)
                lstBattles.Items.Add(lvwi)
            Next
        Catch ex As Exception
            HandleException("ctlCombatResolution.ListBattles", ex)
        End Try
    End Sub

    Private Sub ShowResultIcon(ByRef lvwi As ListViewItem)
        '// shows the appropriate icon for the status of the underlying battle
        Try
            Dim batt As Battle = DirectCast(lvwi.Tag, Battle)
            Select Case batt.BattleResult
                Case BattleResult_cgd.NotFinished : lvwi.ImageIndex = 0
                Case BattleResult_cgd.AttackerVictory : lvwi.ImageIndex = 1
                Case BattleResult_cgd.AttackerMarginalVictory : lvwi.ImageIndex = 2
                Case BattleResult_cgd.Draw : lvwi.ImageIndex = 3
                Case BattleResult_cgd.DefenderVictory : lvwi.ImageIndex = 4
                Case BattleResult_cgd.DefenderMarginalVictory : lvwi.ImageIndex = 5
            End Select
        Catch ex As Exception
            HandleException("ctlCombatResolution.ShowResultIcon", ex)
        End Try
    End Sub

    Private Sub Populate(ByRef batt As Battle_2)
        Try
            Dim faction1, faction2 As Faction

            ListBattleText(batt)

            tvwChits.Nodes.Clear()

            Dim faction1Tree As New CampaignerItemTreeNode
            faction1 = ptrGameData.Faction_g.Item("FACT" & batt.AttackingFactionID)
            faction1Tree.Text = faction1.FactionName
            faction1Tree.ItemType = CampaignerItem_cgd.Faction
            faction1Tree.Item = faction1
            faction1Tree.ImageIndex = 0

            tvwChits.Nodes.Add(faction1Tree)

            Dim faction2Tree As New CampaignerItemTreeNode
            faction2 = ptrGameData.Faction_g.Item("FACT" & batt.DefendingFactionID)
            faction2Tree.Text = faction2.FactionName
            faction2Tree.ItemType = CampaignerItem_cgd.Faction
            faction2Tree.Item = faction2
            faction2Tree.ImageIndex = 1

            tvwChits.Nodes.Add(faction2Tree)

            '// create the popup combat resolutions
            CreatePopupResolutions(faction1, faction2)

            '// list assets
            For Each mem As ChitMember In batt.InvolvedChits
                Dim useTree As CampaignerItemTreeNode
                If mem.OwningFaction.Equals(ptrGameData.Faction_g.Item("FACT" & batt.AttackingFactionID)) Then
                    useTree = faction1Tree
                Else
                    useTree = faction2Tree
                End If

                Dim memberNode As New CampaignerItemTreeNode
                memberNode.Item = mem
                memberNode.Text = mem.Name
                '// add the icon to the icons list
                imlTreeIcons.Images.Add(mem.Name, mem.icon)
                memberNode.ImageKey = mem.Name
                memberNode.SelectedImageKey = mem.Name

                If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                    memberNode.ItemType = CampaignerItem_cgd.Battlegroup
                    '// add any additional units the battlegroup has
                    insertChildren(memberNode)
                ElseIf mem.UnitType = GroundChitClass_cgd.Objective Then
                    Dim inst As InstallationChit = mem
                    memberNode.ItemType = CampaignerItem_cgd.Installation

                    If mem.Status = GroundUnitStatus_cgd.Dead Then
                        memberNode.ImageIndex = 5 '// FIRE!!! HAHAAA!
                        memberNode.SelectedImageIndex = 5
                    Else
                        memberNode.ImageIndex = 4
                        memberNode.SelectedImageIndex = 4
                    End If

                End If

                If mem.Status = GroundUnitStatus_cgd.Dead Then memberNode.ImageIndex = 2 '// DEEEED.

                '// finally add this item to the correct faction tree
                useTree.Nodes.Add(memberNode)

            Next


        Catch ex As Exception
            HandleException("ctlCombatResolution.Populate", ex)
        End Try
    End Sub

    Private Sub insertChildren(ByRef bgnode As CampaignerItemTreeNode)
        Try
            '// adds either bg or unit children
            Dim bg As BattlegroupChit = bgnode.Item
            For Each mem As ChitMember In bg.members
                Dim memNode As New CampaignerItemTreeNode
                memNode.Item = mem

                If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                    memNode.ItemType = CampaignerItem_cgd.Battlegroup
                    If Not imlTreeIcons.Images.ContainsKey(mem.Name) Then
                        imlTreeIcons.Images.Add(mem.Name, mem.icon)
                    End If

                    If mem.Status = GroundUnitStatus_cgd.Dead Then
                        memNode.SelectedImageIndex = 2
                        memNode.ImageIndex = 2
                    Else
                        memNode.ImageKey = mem.Name
                        memNode.SelectedImageKey = mem.Name
                    End If


                    insertChildren(memNode)
                ElseIf mem.UnitType = GroundChitClass_cgd.Unit Then
                    '// we just create a new treenode here...
                    Dim punit As ChitUnitTypeMember = mem
                    If mem.Status = GroundUnitStatus_cgd.Dead Then
                        memNode.ImageIndex = 2
                        memNode.SelectedImageIndex = 2
                    Else
                        memNode.ImageIndex = 3
                        memNode.SelectedImageIndex = 3
                    End If

                    memNode.ItemType = CampaignerItem_cgd.Unit

                End If
                memNode.Text = mem.Name
                bgnode.Nodes.Add(memNode)
            Next

        Catch ex As Exception
            HandleException("ctlCombatResolution.insertChildren", ex)
        End Try
    End Sub

    Private Sub ListBattleText(ByRef batt As Battle_2)
        Try
            Dim terrainName As String = ""
            Dim terrainDesc As String = ""

            ptrFlexMap.TerrainInfoAtCoord(batt.BattleLocation, terrainName, terrainDesc)
            txtTerrainDetails.Text = "This battle occurs in " & terrainName & "." & vbCrLf
            txtTerrainDetails.Text &= "Description: " & terrainDesc & vbCrLf
            txtTerrainDetails.Text &= "Defensive Value: " & ptrFlexMap.DefenseAtCoord(batt.BattleLocation)

        Catch ex As Exception
            txtTerrainDetails.Text = "Error getting terrain information. " & ex.Message
        End Try
    End Sub

    Private Sub CreatePopupResolutions(ByRef faction1 As Faction, ByRef faction2 As Faction)
        Try
            mnuPopup.Items.Clear()

            Dim tsi As New BattleResultToolStripMenuItem
            tsi.Text = "Unresolved"
            tsi.BattleResult = BattleResult_cgd.NotFinished
            tsi.Image = imlBattleResults.Images.Item(0)
            '// add the handler!
            AddHandler tsi.Click, AddressOf BattleResult_Click

            mnuPopup.Items.Add(tsi)

            tsi = New BattleResultToolStripMenuItem
            tsi.Text = faction1.FactionName & " Victory"
            tsi.BattleResult = BattleResult_cgd.AttackerVictory
            tsi.Image = imlBattleResults.Images.Item(1)
            AddHandler tsi.Click, AddressOf BattleResult_Click
            mnuPopup.Items.Add(tsi)

            '// f1 marginal
            tsi = New BattleResultToolStripMenuItem '(faction1.FactionName & " Marginal Victory")
            tsi.Text = faction1.FactionName & " Marginal Victory"
            tsi.BattleResult = BattleResult_cgd.AttackerMarginalVictory
            tsi.Image = imlBattleResults.Images.Item(2)
            AddHandler tsi.Click, AddressOf BattleResult_Click
            mnuPopup.Items.Add(tsi)

            '// draw
            tsi = New BattleResultToolStripMenuItem
            tsi.Text = "Draw"
            tsi.Image = imlBattleResults.Images.Item(3)
            tsi.BattleResult = BattleResult_cgd.Draw
            AddHandler tsi.Click, AddressOf BattleResult_Click
            mnuPopup.Items.Add(tsi)

            '// f2 vict
            tsi = New BattleResultToolStripMenuItem
            tsi.Text = faction2.FactionName & " Victory"
            tsi.Image = imlBattleResults.Images.Item(4)
            tsi.BattleResult = BattleResult_cgd.DefenderVictory
            AddHandler tsi.Click, AddressOf BattleResult_Click
            mnuPopup.Items.Add(tsi)

            '// f2 marginal
            tsi = New BattleResultToolStripMenuItem
            tsi.Text = faction2.FactionName & " Marginal Victory"
            tsi.Image = imlBattleResults.Images.Item(5)
            tsi.BattleResult = BattleResult_cgd.DefenderMarginalVictory
            AddHandler tsi.Click, AddressOf BattleResult_Click
            mnuPopup.Items.Add(tsi)

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub lstBattles_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstBattles.MouseUp
        If e.Button = Windows.Forms.MouseButtons.Right Then
            If lstBattles.SelectedItems.Count = 0 Then Exit Sub
            '// if there is ONLY an installation selected, the option "Change Owner" will be available.
            mnuPopup.Show(lstBattles, e.Location)
        End If
    End Sub

    Private Sub CheckInstallationOnlySelected()
        Try
            Dim instonly As Boolean = True

            '// these are the top level (faction) nodes. Ignore them, but bounce through their children
            For Each cnode As CampaignerItemTreeNode In tvwChits.Nodes
                If FoundNonInstallation(cnode) Then
                    instonly = False
                    Exit For
                End If
            Next

            mnuOwner.Enabled = instonly

        Catch ex As Exception
            HandleException("ctlCombatResolution.CheckInstallationOnlySelected", ex)
        End Try
    End Sub

    Private Function FoundNonInstallation(ByRef cNode As CampaignerItemTreeNode) As Boolean
        Dim foundNonInst As Boolean = False

        For Each childNode As CampaignerItemTreeNode In cNode.Nodes
            If childNode.Checked = True Then
                If childNode.ItemType = CampaignerItem_cgd.Unit Then
                    Return True
                ElseIf childNode.ItemType = CampaignerItem_cgd.Battlegroup Then
                    Return True
                End If
            End If
            foundNonInst = FoundNonInstallation(childNode)
            If foundNonInst = True Then Return True
        Next

        Return False

    End Function

    Private Sub lstBattles_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstBattles.SelectedIndexChanged
        If lstBattles.SelectedItems.Count = 0 Then Exit Sub

        Populate(DirectCast(lstBattles.SelectedItems(0).Tag, Battle_2))

    End Sub

    Private Sub btnApplyResults_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnApplyResults.Click
        Dim allfinished As Boolean = True

        For Each battkey As String In ptrGameData.Battles_g.HT.Keys
            Dim batt As Battle = ptrGameData.Battles_g.Item(battkey)
            If batt.BattleResult = BattleResult_cgd.NotFinished Then
                allfinished = False
                Exit For
            End If
        Next

        If allfinished = False Then
            Dim messRes As DialogResult = MessageBox.Show("Not all battles have a resolution. Click YES to set all unfinished battles to DRAW. Click NO to set the results yourself." & vbCrLf & "Do you wish to set the unfinished battles to DRAW?", "Not All Battles Resolved", MessageBoxButtons.YesNo)
            If messRes = DialogResult.Yes Then
                For Each battkey As String In ptrGameData.Battles_g.HT.Keys
                    Dim batt As Battle = ptrGameData.Battles_g.Item(battkey)
                    If batt.BattleResult = BattleResult_cgd.NotFinished Then batt.BattleResult = BattleResult_cgd.Draw
                Next
            Else
                '// manually set outcome
                Exit Sub
            End If
        End If

        RaiseEvent AllBattlesFinished()
    End Sub

    Private Sub BattleResult_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            '// this happens when the user selects an outcome for a battle from the popup.
            '// we have to set the resolution for each selected battle, as well as change the icon to the appropriate one.
            If lstBattles.SelectedItems.Count = 0 Then Exit Sub

            Dim batt As Battle
            Dim lvwi As ListViewItem
            Dim battleResult As BattleResultToolStripMenuItem = DirectCast(sender, BattleResultToolStripMenuItem)

            For Each lvwi In lstBattles.SelectedItems
                batt = DirectCast(lvwi.Tag, Battle)
                batt.BattleResult = battleResult.BattleResult
                '// update the icon
                ShowResultIcon(lvwi)
            Next

        Catch ex As Exception
            HandleException("ctlCombatResolution.BattleResult_Click", ex)
        End Try
    End Sub

    Private Sub tvwChits_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvwChits.AfterCheck
        Try
            '// make everything beneath have the same check. :)
            If e.Node.Checked Then
                For Each node As TreeNode In e.Node.Nodes
                    node.Checked = True
                Next
            End If

            '// make the parent UNCHECKED if this one is unchecked as well. Yeah.
            If e.Node.Checked = False Then
                If Not e.Node.Parent Is Nothing Then
                    e.Node.Parent.Checked = False
                End If
            End If

        Catch ex As Exception

        End Try
    End Sub

    Private Sub tvwChits_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tvwChits.MouseUp
        Try
            If e.Button = Windows.Forms.MouseButtons.Right Then
                CheckInstallationOnlySelected()
                mnuKill.Show(tvwChits, e.Location)
            End If

        Catch ex As Exception
            HandleException("ctlCombatResolution.twvChits_MouseUp", ex)
        End Try
    End Sub

    Private Sub mnuKillMember_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuKillMember.Click
        Try
            Dim no As CampaignerItemTreeNode
            For Each no In tvwChits.Nodes
                If no.ItemType = CampaignerItem_cgd.Faction Then
                    For Each memNode As CampaignerItemTreeNode In no.Nodes
                        ApplyDeadStatus(memNode)
                    Next
                End If
            Next

        Catch ex As Exception
            HandleException("ctlCombatResolution.MemberStatus_Click", ex)
        End Try
    End Sub


    Private Sub mnuElementManager_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuElementManager.Click
        Try
            Dim no As CampaignerItemTreeNode
            no = tvwChits.SelectedNode
            If no Is Nothing Then Exit Sub

            Select Case no.ItemType
                Case CampaignerItem_cgd.Unit
                    Dim eman As New frmElementPicker(ptrGameData, no.Item)
                    eman.ShowDialog()
            End Select
        Catch ex As Exception

        End Try
    End Sub

    Private Sub ApplyDeadStatus(ByRef no As CampaignerItemTreeNode)
        Try
            If no.Checked Then
                DirectCast(no.Item, ChitMember).Status = GroundUnitStatus_cgd.Dead
                DirectCast(no.Item, ChitMember).PreviousStatus = DirectCast(no.Item, ChitMember).Status
                If no.ItemType = CampaignerItem_cgd.Installation Then
                    no.ImageIndex = 5
                    no.SelectedImageIndex = 5
                Else
                    no.ImageIndex = 2
                    no.SelectedImageIndex = 2
                End If
                
            End If

            For Each memNode As CampaignerItemTreeNode In no.Nodes
                ApplyDeadStatus(memNode)
            Next

        Catch ex As Exception
            HandleException("ctlCombatResolution.ApplyDeadStatus", ex)
        End Try
    End Sub

    Private Sub ApplyPreviousStatus(ByRef no As CampaignerItemTreeNode)
        Try
            If no.Checked Then
                DirectCast(no.Item, ChitMember).Status = DirectCast(no.Item, ChitMember).PreviousStatus 'GroundUnitStatus_cgd.Dead
                If DirectCast(no.Item, ChitMember).UnitType = GroundChitClass_cgd.Battlegroup Then
                    no.ImageKey = no.Text 'DirectCast(no.Tag, BattlegroupChit).Name
                    no.SelectedImageKey = no.Text ' DirectCast(no.Tag, BattlegroupChit).Name
                ElseIf no.ItemType = CampaignerItem_cgd.Installation Then
                    no.ImageKey = 4
                    no.SelectedImageIndex = 4
                Else
                    no.ImageIndex = 3
                    no.SelectedImageIndex = 3
                End If
            End If

            For Each memNode As CampaignerItemTreeNode In no.Nodes
                ApplyPreviousStatus(memNode)
            Next
        Catch ex As Exception
            HandleException("ctlCombatResolution.ApplyPreviousStatus", ex)
        End Try
    End Sub

    Private Sub mnuRestore_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuRestore.Click
        Try
            Dim no As CampaignerItemTreeNode
            For Each no In tvwChits.Nodes
                If no.ItemType = CampaignerItem_cgd.Faction Then
                    For Each memNode As CampaignerItemTreeNode In no.Nodes
                        ApplyPreviousStatus(memNode)
                    Next
                End If
            Next
        Catch ex As Exception
            HandleException("ctlCombatResolution.MemberStatus_Click", ex)
        End Try
    End Sub

    Private Sub mnuOwner_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuOwner.Click
        Try
            '// will swap the owner of the checked installation (and ONLY the checked installation)
            Dim cnode As CampaignerItemTreeNode
            For Each cnode In tvwChits.Nodes
                SwapInstallationOwnership(cnode)
            Next
        Catch ex As Exception
            HandleException("ctlCombatResolution.MemberStatus_Click", ex)
        End Try
    End Sub

    Private Sub SwapInstallationOwnership(ByRef cnode As CampaignerItemTreeNode)
        Try
            Dim childNode As CampaignerItemTreeNode
            Dim SwapExecuted As Boolean = False

            Try
                If cnode.Nodes.Count = 0 Then Exit Sub
            Catch ex As Exception
                Exit Sub
            End Try

            For Each childNode In cnode.Nodes
                If childNode.ItemType = CampaignerItem_cgd.Installation Then
                    If childNode.Checked Then
                        '// swap!
                        Dim f1 As Faction = DirectCast(tvwChits.Nodes.Item(0), CampaignerItemTreeNode).Item
                        Dim f2 As Faction = DirectCast(tvwChits.Nodes.Item(1), CampaignerItemTreeNode).Item

                        If DirectCast(childNode.Item, InstallationChit).OwningFaction.Equals(f1) Then
                            DirectCast(childNode.Item, InstallationChit).OwningFaction = f2
                        Else
                            DirectCast(childNode.Item, InstallationChit).OwningFaction = f1
                        End If
                        SwapExecuted = True

                    End If
                End If
            Next

            If SwapExecuted Then
                Populate(lstBattles.SelectedItems(0).Tag)
            End If

        Catch ex As Exception
            HandleException("ctlCombatResolution.SwapInstallationOwnership", ex)
        End Try
    End Sub

    Private Sub mnuPopup_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles mnuPopup.Opening

    End Sub

End Class



Public Class BattleResultToolStripMenuItem : Inherits ToolStripMenuItem
    Private _battresult As BattleResult_cgd = BattleResult_cgd.NotFinished

    Public Property BattleResult() As BattleResult_cgd
        Get
            Return _battresult
        End Get
        Set(ByVal value As BattleResult_cgd)
            _battresult = value
        End Set
    End Property


End Class